﻿using System;
using System.Collections.Generic;


namespace HyxFrame.Core
{
    public class WebSocketManager : MonoSingleton<WebSocketManager>
    {
        private Dictionary<string, WebSocket> dic_WebSocket = new Dictionary<string, WebSocket>();

        protected override void InitManager()
        {

        }

        /// <summary>
        /// 创建一份webscoket链接
        /// </summary>
        /// <param name="socketName">socket 名称</param>
        /// <param name="url">链接地址</param>
        /// <param name="action">接受消息回调</param>
        public WebSocket CreateNewSocket(string socketName, string url, Action<string> action)
        {
            WebSocket socket = GetWebSocket(socketName);
            if (socket == null)
            {
                socket = new WebSocket(url, action);
                dic_WebSocket.Add(socketName, socket);
            }
            return socket;
        }

        /// <summary>
        /// 关闭指定的websocket链接
        /// </summary>
        /// <param name="socketName">socket 名称</param>
        public void DestroySocket(string socketName)
        {
            dic_WebSocket[socketName].CloseClientWebSocket();
        }

        /// <summary>
        /// 根据名称获取对应的  socket
        /// </summary>
        /// <param name="socketName">socket 名称</param>
        /// <returns></returns>
        public WebSocket GetWebSocket(string socketName)
        {
            WebSocket socket;
            dic_WebSocket.TryGetValue(socketName, out socket);
            return socket;
        }


        protected override void OnDestroy()
        {
            base.OnDestroy();
            foreach (var item in dic_WebSocket)
            {
                item.Value.CloseClientWebSocket();
            }

        }
    }

}